package com.liuyjy.encryptDecrypt;

import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Author liuyjy
 * @Date 2025/2/20 13:47
 * @Description: 开关控制逻辑
 **/
@Component
public class CryptoInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            boolean enabled = isCryptoEnabled(method);

            // 将开关状态存储到 RequestAttributes 中
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute(
                        "CRYPTO_ENABLED", enabled, RequestAttributes.SCOPE_REQUEST);
            }
        }
        return true;
    }

    private boolean isCryptoEnabled(HandlerMethod method) {
        // 优先级：方法注解 > 类注解 > 默认关闭
        EncryptDecrypt methodAnnotation = method.getMethodAnnotation(EncryptDecrypt.class);
        if (methodAnnotation != null) return true;

        EncryptDecrypt classAnnotation = method.getBeanType().getAnnotation(EncryptDecrypt.class);
        return classAnnotation != null;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        // 清理开关状态
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            requestAttributes.removeAttribute("CRYPTO_ENABLED", RequestAttributes.SCOPE_REQUEST);
        }
    }
}

